<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);
$orderId = intval($input['order_id'] ?? 0);
$filename = $input['filename'] ?? '';

if ($orderId <= 0 || empty($filename)) {
    echo json_encode(['success' => false, 'message' => '参数无效']);
    exit;
}

$db = getDB();

// 查找包含该截图的操作记录
$stmt = $db->prepare("SELECT id, screenshots FROM order_operations WHERE order_id = ? AND screenshots LIKE ?");
$stmt->execute([$orderId, '%' . $filename . '%']);
$operations = $stmt->fetchAll();

if (empty($operations)) {
    echo json_encode(['success' => false, 'message' => '未找到对应的操作记录']);
    exit;
}

// 从所有相关操作记录中删除该截图
foreach ($operations as $operation) {
    $screenshots = json_decode($operation['screenshots'], true);
    if (is_array($screenshots)) {
        $newScreenshots = array_filter($screenshots, function($screenshot) use ($filename) {
            return $screenshot !== $filename;
        });
        
        // 更新操作记录
        $stmt = $db->prepare("UPDATE order_operations SET screenshots = ? WHERE id = ?");
        $stmt->execute([json_encode(array_values($newScreenshots)), $operation['id']]);
    }
}

// 删除物理文件
deleteFile($filename, 'settlement_screenshot');

echo json_encode(['success' => true, 'message' => '截图删除成功']);
?>